package cn.fl.custpay.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.user.facade.framework.constant.DictionaryConstant;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.custpay.condition.CmmOlRecordDetailQueryCondition;
import cn.fl.custpay.service.ICmmRechargeRecordService;
import cn.fl.custpay.vo.CmmDeductedOrderVO;
import cn.fl.custpay.vo.CmmOlRecordDetailVO;
import cn.fl.custpay.vo.CmmRechargeRecordVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @ClassName CmmOrderQueryController
 * @Description 订单查询 控制层
 * @Author shijb
 * @Date 2018/7/2 11:33
 * @Version 1.0
 **/
@Controller
@RequestMapping("/custpay/cmmOrderQuery")
public class CmmOrderQueryController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CmmOrderQueryController.class);

    @Autowired
    private ICmmRechargeRecordService cmmRechargeRecordService;

    @RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("custpay/cmmOrderQuery/cmmOrderQueryList");
        return view;
    }

    /**
     * 初始化
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initcmmOrderQueryList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long staTime = System.currentTimeMillis();
        String orderid = request.getParameter("orderid");
        BaseLogUtils.info(logger, "initList", "初始化订单查询. 参数传入:"+ JSONObject.toJSONString(orderid) , CurrentThreadContext.getCurrentUserName());

        if (StringUtils.isEmpty(orderid)) {
            BaseLogUtils.info(logger, "initList", "查询数据失败. 入口参数订单id不能为空:");
            return new ListPageVO<CmmDeductedOrderVO>(null, 1);
        }
        //TODO SOMETHING
        CmmRechargeRecordVO cmmRechargeRecordVO = this.cmmRechargeRecordService.unifyDeductedQuery(Long.valueOf(orderid));
        if (null == cmmRechargeRecordVO) {
            BaseLogUtils.info(logger, "initList", "查询数据失败.返回数据不存在");
            return new ListPageVO<CmmDeductedOrderVO>(null, 1);
        }

        Integer daikouResult = cmmRechargeRecordVO.getIsSuc() != null ? cmmRechargeRecordVO.getIsSuc() : null;
        String daikouResultDesc = cmmRechargeRecordVO.getResultDesc() != null ? cmmRechargeRecordVO.getResultDesc() : "";
        Long payAmt = cmmRechargeRecordVO.getPaymentMoney() != null ? cmmRechargeRecordVO.getPaymentMoney() : null;
        String payDate = DateUtils.formatDateToString(cmmRechargeRecordVO.getPayDate(),DateUtils.YYYY_MM_DDHHMMSS);
        Long payType = cmmRechargeRecordVO.getPayType() != null ? cmmRechargeRecordVO.getPayType() : null;

        CmmDeductedOrderVO cmmDeductedOrderVO = new CmmDeductedOrderVO();
        cmmDeductedOrderVO.setOrderId(Long.valueOf(orderid));
        if(StringUtils.isNotEmpty(daikouResult)){
            Map<String,String> sumap =  this.cmmRechargeRecordService.getDictionryMap(DictionaryConstant.SYS_WITHOLD_RES_CD);
            if(sumap != null){
                cmmDeductedOrderVO.setDaikouResult(sumap.get(String.valueOf(daikouResult)));
            }
        }
        cmmDeductedOrderVO.setDaikouResultDesc(daikouResultDesc);
        cmmDeductedOrderVO.setDaikouTime(payDate);
        if(StringUtils.isNotEmpty(payAmt)){
            cmmDeductedOrderVO.setPayAmt(DecimalUtils.convertFenToYuan(payAmt));
        }
        if(StringUtils.isNotEmpty(payType)){
            Map<String,String> paytypemap =  this.cmmRechargeRecordService.getDictionryMap(DictionaryConstant.SYS_PAY_CHANNEL_CD);
            if(paytypemap != null){
                cmmDeductedOrderVO.setPayType(paytypemap.get(String.valueOf(payType)));
            }
        }
        BaseLogUtils.info(logger, "initList", "查询订单响应数据:" + JSONObject.toJSONString(cmmDeductedOrderVO));
        List<CmmDeductedOrderVO> list = new ArrayList<>();
        list.add(cmmDeductedOrderVO);
        ListPageVO<CmmDeductedOrderVO> listPage = new ListPageVO<CmmDeductedOrderVO>(list, 1);
        Long endTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "查询数据完成.耗时:" + (endTime - staTime) + "毫秒");
        return listPage;
    }


    /**
     * 根据平台订单号查询
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getByOrderId.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object getByOrderId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String orderid = request.getParameter("orderid");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if(StringUtils.isEmpty(orderid)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("平台订单号为空!");
            BaseLogUtils.error(logger, "getByOrderId", "获取渠道信息,平台订单号不存在.[localSeqId="+orderid+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CmmRechargeRecordVO vo = this.cmmRechargeRecordService.unifyDeductedQuery(Long.valueOf(orderid));
            //cmmRechargeRecordService.paautodecoposeFund();
            if(null == vo){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getByOrderId", "获取订单信息,数据不存在.[id="+orderid+"]", CurrentThreadContext.getCurrentUserName());
            }

            result.setData(vo);
            BaseLogUtils.info(logger, "getByOrderId", "获取订单信息.[id="+orderid+"]", CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取信息失败,主键["+orderid+"].", CurrentThreadContext.getCurrentUserName(),ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getByOrderId", "根据平台订单号获取信息失败,主键["+orderid+"].", CurrentThreadContext.getCurrentUserName(),ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getByOrderId", "根据平台订单号获取对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }


    /**
     * 修改同步狮桥放款记录
     */
    @RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改渠道对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        //主键Id
        String id = request.getParameter("id");

        //扣款金额
        String paymentMoneydou = request.getParameter("payAmt");

        //结果描述
        String resultDesc = request.getParameter("daikouResultDesc");

        //代扣结果
        String daikouResult = request.getParameter("daikouResult");

        //扣款时间
        String payDate = request.getParameter("daikouTime");
        //支付平台
        String payTypeNm = request.getParameter("payTypeNm");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "同步成功!");
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.info(logger, "modify", "修改订单信息,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        CmmRechargeRecordVO entity = null;
        try {
            entity = new CmmRechargeRecordVO();

            if (StringUtils.isNotEmpty(paymentMoneydou)){
                entity.setPaymentMoneydou(Double.valueOf(paymentMoneydou.toString()));
            }
            if (StringUtils.isNotEmpty(resultDesc)){
                entity.setResultDesc(resultDesc);
            }
            if (StringUtils.isNotEmpty(payDate)){
                entity.setPayDate(DateUtils.formatStringToDate(payDate, DateUtils.YYYYMMDDHHMMSS));
            }
            if (StringUtils.isNotEmpty(payTypeNm)){
                entity.setPayTypeNm(payTypeNm);
            }
            if(StringUtils.isNotEmpty(daikouResult)){
                Integer inSuc = 0;
                switch (daikouResult){
                    case "失败":
                        inSuc =0;
                        break;
                    case "成功":
                        inSuc =1;
                        break;
                    case "未支付":
                        inSuc =2;
                        break;
                    case "处理中":
                        inSuc =3;
                        break;
                }
                entity.setIsSuc(inSuc);
            }



            entity.setId(Long.parseLong(id));
            entity.setMdfTm(new Date());
            boolean success = this.cmmRechargeRecordService.modify(entity);
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改订单信息失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改订单信息成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改订单信息失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改订单信息失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }


    /**
     * 企业订单同步
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/paautodecoposeFund.do", method = { RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public DataResultVO paautodecoposeFund(HttpServletRequest request, HttpServletResponse response) {

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "已发起企业订单同步，请稍后查看同步结果");
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "paautodecoposeFund", "企业同步订单状态,平台id不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        BaseLogUtils.info(logger, "paautodecoposeFund", "发起企业订单同步====开始", CurrentThreadContext.getCurrentUserName());
        CmmRechargeRecordVO vo = cmmRechargeRecordService.selectById(Long.parseLong(id));
        BaseLogUtils.info(logger, "paautodecoposeFund", "企业订单同步====获取到的订单对象信息是 vo", JSONObject.toJSONString(vo));
        if(vo == null){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "paautodecoposeFund", "企业同步订单状态,订单不存在[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        this.cmmRechargeRecordService.paautodecoposeFund(vo);
        BaseLogUtils.info(logger, "paautodecoposeFund", "已发起企业订单同步====结束", CurrentThreadContext.getCurrentUserName());
        return result;
    }




}
